<template>
    <view class="weather-container">
        <!-- 今日天气信息头部 -->
        <view class="today-header">
            <view class="location" @click="goToCitySelector">
                <text class="location-icon">📍</text>
                <text class="city-name">{{ todayWeatherData.city }}</text>
            </view>
            <view class="current-temp">
                <text class="temp-value">{{ todayWeatherData.temperature }}°</text>
                <view class="temp-detail">
                    <text class="temp-icon">{{ todayWeatherData.icon }}</text>
                    <text class="temp-status">{{ todayWeatherData.status }}</text>
                </view>
            </view>
        </view>

        <!-- 加载状态 -->
        <view v-if="loading" class="loading-state">
            <text class="loading-text">正在获取天气信息...</text>
        </view>
        
        <!-- 错误状态 -->
        <view v-if="error" class="error-state">
            <text class="error-text">{{ error }}</text>
            <view class="retry-btn" @click="getWeatherData">重试</view>
        </view>

        <!-- 多日天气预报卡片区 -->
        <view v-if="!loading && !error" class="forecast-section">
            <scroll-view 
                class="cards-scroll" 
                scroll-x 
                show-scrollbar="false" 
                enhanced="true" 
                :bounces="true"
                @scroll="handleScroll"
                @scrollend="handleScrollEnd">
                <view 
                    v-for="(item, index) in forecastData" 
                    :key="item.date"
                    :id="`card-${index}`"
                    class="forecast-card"
                    :class="{ 'active': activeCardIndex === index }"
                    @click="activeCardIndex = index">
                    <view class="card-inner">
                        <view class="card-date">
                            <text class="day">周{{ convertWeekToChinese(item.week) }}</text>
                            <text class="date">{{ formatDate(item.date) }}</text>
                        </view>
                        <view class="weather">
                            <text class="temperature">{{ item.daytemp }}-{{ item.nighttemp }}°</text>
                            <text class="weather-icon">{{ getWeatherIcon(item.dayweather) }}</text>
                        </view>
                        <view class="suggestion">
                            <text class="suggestion-icon">{{ getSuggestionIcon(item.dayweather) }}</text>
                            <text class="suggestion-text">{{ getWeatherSuggestion(item.dayweather) }}</text>
                        </view>
                    </view>
            </view>
            </scroll-view>
        </view>
    </view>
</template>

<script setup>
import { ref, onMounted, onUnmounted, defineExpose } from 'vue';
import { getWeather,getIpLocation } from '../../api/GaoDeApi';
import { getLastLocation } from '../../api/location';

// 状态变量
const loading = ref(false);
const error = ref('');

// 今日天气数据
const todayWeatherData = ref({
    city: '加载中...',
    temperature: '--',
    status: '加载中',
    icon: '🔄',
});

// 预报数据
const forecastData = ref([]);

// 天气图标映射
const weatherIconMap = {
    '晴': '☀️',
    '多云': '⛅',
    '阴': '☁️',
    '小雨': '🌧️',
    '中雨': '🌧️',
    '大雨': '🌧️',
    '暴雨': '⛈️',
    '雷阵雨': '🌩️',
    '小雪': '❄️',
    '中雪': '❄️',
    '大雪': '❄️',
    '暴雪': '❄️',
    '雨夹雪': '🌨️',
    '扬沙': '🌫️',
    '浮尘': '🌫️',
    '雾': '🌫️',
    '霾': '🌫️'
};

// 天气建议映射
const weatherSuggestionMap = {
    '晴': '适宜外出，注意防晒',
    '多云': '适合户外活动',
    '阴': '适宜出行',
    '小雨': '建议带伞',
    '中雨': '建议带伞',
    '大雨': '尽量待在室内',
    '暴雨': '尽量待在室内',
    '雷阵雨': '尽量待在室内',
    '小雪': '注意保暖',
    '中雪': '注意保暖',
    '大雪': '尽量待在室内',
    '暴雪': '尽量待在室内',
    '雨夹雪': '注意保暖',
    '扬沙': '佩戴口罩出行',
    '浮尘': '佩戴口罩出行',
    '雾': '减少户外活动',
    '霾': '减少户外活动'
};
const currentCity = ref({});
// 活跃卡片索引
const activeCardIndex = ref(0);

// 卡片自动滚动控制
let scrollTimer = null;
let isUserScrolling = ref(false);
let scrollTimeout = null;

// 将阿拉伯数字周数转换为中文数字
const convertWeekToChinese = (week) => {
    const weekMap = {
        '1': '一',
        '2': '二',
        '3': '三',
        '4': '四',
        '5': '五',
        '6': '六',
        '7': '日',
        '0': '日'
    };
    return weekMap[week] || week;
};

// 格式化日期
const formatDate = (dateStr) => {
    const date = new Date(dateStr);
    const month = date.getMonth() + 1;
    const day = date.getDate();
    return `${month}月${day}日`;
};

// 获取天气图标
const getWeatherIcon = (weather) => {
    return weatherIconMap[weather] || '🌈';
};

// 获取建议图标
const getSuggestionIcon = (weather) => {
    const suggestion = getWeatherSuggestion(weather);
    const map = {
        '适宜外出，注意防晒': '🧴',
        '适合户外活动': '🏃',
        '适宜出行': '🚗',
        '建议带伞': '☂️',
        '尽量待在室内': '🏠',
        '注意保暖': '🧣',
        '佩戴口罩出行': '😷',
        '减少户外活动': '🏠'
    };
    return map[suggestion] || '📝';
};
const handleLocationClick = () => {
    uni.navigateTo({
        url: '/pages/commpoent/findcity'
    });
};
// 获取天气建议
const getWeatherSuggestion = (weather) => {
    return weatherSuggestionMap[weather] || '适宜出行';
};

// 获取天气预报
const getWeatherData = async () => {
    loading.value = true;
    error.value = '';
    console.log('正在获取城市天气:', currentCity.value);
    
    if (!currentCity.value || !currentCity.value.adcode) {
        console.error('城市代码无效');
        error.value = '城市信息无效，请重新选择城市';
        loading.value = false;
        return;
    }
    
    try {
        const res = await getWeather({
            city: currentCity.value.adcode,
            extensions: 'all',
        });
        
        console.log('天气API返回数据:', res);
        
        // 检查API返回是否成功
        if (res.data && res.data.status === "1" && res.data.forecasts && res.data.forecasts.length > 0) {
            const weatherData = res.data.forecasts[0];
            
            // 更新城市信息
            todayWeatherData.value.city = weatherData.city || currentCity.value.city || '未知城市';
            
            // 如果有预报数据
            if (weatherData.casts && weatherData.casts.length > 0) {
                // 今天的数据
                const today = weatherData.casts[0];
                todayWeatherData.value.temperature = today.daytemp;
                todayWeatherData.value.status = today.dayweather;
                todayWeatherData.value.icon = getWeatherIcon(today.dayweather);
                
                // 预报数据
                forecastData.value = weatherData.casts;
                
                // 重置活跃卡片索引
                activeCardIndex.value = 0;
                
                // 发送天气更新事件
                uni.$emit('weather-updated', weatherData.casts);
                
                console.log('天气数据更新成功');
            }
        } else {
            console.error('API返回数据异常:', res);
            error.value = res.data && res.data.info 
                ? `获取天气失败: ${res.data.info}` 
                : '获取天气数据失败，请稍后重试';
        }
    } catch (err) {
        console.error('获取天气数据出错:', err);
        error.value = '网络异常，请检查网络连接后重试';
    } finally {
        loading.value = false;
    }
};
//获取当前定位
const getCurrentLocation = async () => {
    await getIpLocation().then(res => {
        currentCity.value = res.data;
        console.log('当前城市:', currentCity.value);
        getWeatherData();
    });
};
// 处理滚动事件
const handleScroll = () => {
    isUserScrolling.value = true;
    
    if (scrollTimeout) {
        clearTimeout(scrollTimeout);
    }
    
    scrollTimeout = setTimeout(() => {
        isUserScrolling.value = false;
    }, 3000);
};

// 处理滚动结束事件
const handleScrollEnd = (e) => {
    // 这里可以添加逻辑来确定当前可见的卡片
};

// 跳转到城市选择页面
const goToCitySelector = () => {
  uni.navigateTo({
    url: '/pages/commpoent/findcity?source=weather'
  });
};

// 组件挂载时获取数据
onMounted(() => {
    const userInfo = uni.getStorageSync('userInfo');
    getLastLocation(userInfo.id).then(res => {
        console.log('获取最后访问城市:', res);
        if(res.data){
            currentCity.value = res.data;
            getWeatherData();
        }else{
            getCurrentLocation();
        }
    })
    // 监听城市选择事件
    uni.$on('city-selected-weather', (selectedCity) => {
        console.log('天气页面接收到城市选择事件:', selectedCity);
        if (selectedCity) {
            currentCity.value = selectedCity.cityName || selectedCity.name || selectedCity.city;
            currentAdcode.value = selectedCity.adcode;
            // 获取所选城市的天气
            getWeatherData();
        }
    });
});

// 组件卸载时清理定时器和事件监听
onUnmounted(() => {
    if (scrollTimer) clearTimeout(scrollTimer);
    if (scrollTimeout) clearTimeout(scrollTimeout);
    
    // 移除事件监听，避免内存泄漏
    uni.$off('city-selected-weather');
});

// 暴露方法供父组件调用
defineExpose({
    getWeatherData
});
</script>

<style scoped lang="scss">
// 颜色变量
$background-color: #f9f9f9;
$card-background: #ffffff;
$text-primary: #000000;
$text-secondary: #666666;
$accent-color: #007aff;
$card-shadow: 0 8px 20px rgba(0, 0, 0, 0.08);
$error-color: #ff3b30;

.weather-container {
    padding: 20px;
    font-family: -apple-system, BlinkMacSystemFont, 'SF Pro Display', sans-serif;
    
    // 今日天气信息头部
    .today-header {
        display: flex;
        justify-content: space-between;
        align-items: center;
        margin-bottom: 20px;
        
        .location {
            display: flex;
            align-items: center;
            
            .location-icon {
                font-size: 16px;
                margin-right: 6px;
            }
            
            .city-name {
                font-size: 18px;
                font-weight: 600;
                color: $text-primary;
            }
        }
        
        .current-temp {
            display: flex;
            align-items: center;
            
            .temp-value {
                font-size: 24px;
                font-weight: 300; // 苹果风格常使用较细的字重
                color: $text-primary;
                margin-right: 12px;
            }
            
            .temp-detail {
                display: flex;
                align-items: center;
                
                .temp-icon {
                    font-size: 18px;
                    margin-right: 6px;
                }
                
                .temp-status {
                    font-size: 16px;
                    color: $text-secondary;
                }
            }
        }
    }
    
    // 加载和错误状态
    .loading-state, .error-state {
        display: flex;
        flex-direction: column;
        align-items: center;
        justify-content: center;
        padding: 40px 0;
        
        .loading-text, .error-text {
            font-size: 16px;
            color: $text-secondary;
            margin-bottom: 16px;
        }
        
        .error-text {
            color: $error-color;
        }
        
        .retry-btn {
            padding: 8px 16px;
            background-color: $accent-color;
            color: white;
            border-radius: 8px;
            font-size: 14px;
            font-weight: 500;
        }
    }
    
    // 预报部分
    .forecast-section {
        // 滚动区域
        .cards-scroll {
            width: 100%;
            white-space: nowrap;
            overflow-x: auto;
            -webkit-overflow-scrolling: touch;
            scroll-behavior: smooth;
            padding: 10px 0;
            
            // 隐藏滚动条
            &::-webkit-scrollbar {
                display: none;
            }
            
            // 预报卡片
            .forecast-card {
                display: inline-block;
            width: 60%;
                margin-right: 15px;
                border-radius: 16px;
                background-color: $card-background;
                box-shadow: $card-shadow;
                transform: scale(0.95);
                transition: all 0.3s ease;
                
                &:first-child {
                    margin-left: 5px;
                }
                
                &.active {
                    transform: scale(1);
                }
                
                .card-inner {
                    padding: 20px;
                    
                    .card-date {
                        margin-bottom: 15px;
            display: flex;
            align-items: center;

                        .day {
                            font-size: 18px;
                            font-weight: 600;
                            color: $text-primary;
                            display: block;
                        }
                        
                        .date {
                            margin-left: 10px;
                            font-size: 14px;
                            color: $text-secondary;
                        }
                    }
                    
                    .weather {
                        display: flex;
                        justify-content: space-between;
                        align-items: center;
                        margin-bottom: 20px;
                        
                        .temperature {
                            font-size: 22px;
                            font-weight: 300;
                            color: $text-primary;
                        }
                        
                        .weather-icon {
                            font-size: 24px;
                        }
                    }
                    
                    .suggestion {
                        display: flex;
                        align-items: center;
                        background-color: rgba($accent-color, 0.1);
                        padding: 8px 12px;
                        border-radius: 8px;
                        
                        .suggestion-icon {
                            font-size: 16px;
                            margin-right: 8px;
                        }
                        
                        .suggestion-text {
                            font-size: 14px;
                            color: $accent-color;
                        }
                    }
                }
            }
        }
    }
}
</style>
